package config

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"path/filepath"
)

type AppConfig struct {
	BasePath     string `json:"BasePath"`
	MaxFileSize  uint64 `json:"MaxFileSize"`
	Host         string `json:"Host"`
	Port         int    `json:"Port"`
	Protocol     string `json:"Protocol"`
	StaticPrefix string `json:"StaticPrefix"`
	UploadPrefix string `json:"UploadPrefix"`
	UploadName   string `json:"UploadName"`
}

var defaultConf string = `
{
	"BasePath": "./storage/",
	"MaxFileSize": 10240000,
	"Host": "",
	"Port": 8848,
	"Protocol": "tcp4",
	"StaticPrefix": "/static",
	"UploadPrefix": "/upload",
	"UploadName": "file"
}
`

var defaultHtml string = `
<html>
<head>
    <title>多文件上传</title>
</head>
<body>
<h2>文件系统上传</h2>
<form action="%s" method="post" enctype="multipart/form-data">
	<input type="text" name="scene" />
	<input type="%s" name="file" multiple="multiple">
	<input type="submit" value="上传" />
</form>
</body>
</html>
`

var (
	config *AppConfig
)

func init() {
	args := os.Args
	abs, errAbs := filepath.Abs(filepath.Dir(args[0]))
	if errAbs != nil {
		panic("sysytem error")
	}

	// 创建 conf文件夹
	_, confErr := os.Stat(abs + "/" + "conf")
	if os.IsNotExist(confErr) {
		err := os.Mkdir(abs+"/"+"conf", 0644)
		if err != nil {
			return
		}
	}

	// 创建 html文件夹
	_, htmlErr := os.Stat(abs + "/" + "html")
	if os.IsNotExist(htmlErr) {
		err := os.Mkdir(abs+"/"+"html", 0644)
		if err != nil {
			return
		}
	}

	_, appConf := os.Stat(abs + "/" + "conf/app.conf")
	if os.IsNotExist(appConf) {
		file, err := os.OpenFile(abs+"/"+"conf/app.conf", os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			panic("open new conf file error")
		}
		_, err = file.Write([]byte(defaultConf))
		if err != nil {
			panic("sysytem error")
		}
		err = file.Close()
		if err != nil {
			panic("sysytem error")
		}
	} else {
		file, err := ioutil.ReadFile(abs + "/" + "conf/app.conf")
		if err != nil {
			panic("open conf file error")
		}
		defaultConf = string(file)
	}
	err := json.Unmarshal([]byte(defaultConf), &config)
	if err != nil {
		panic("parse conf file error")
	}

	_, appHtml := os.Stat(abs + "/" + "html/index.html")
	if os.IsNotExist(appHtml) {
		file, err := os.OpenFile(abs+"/"+"html/index.html", os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			return
		}
		_, err = file.Write([]byte(defaultHtml))
		if err != nil {
			return
		}
		err = file.Close()
		if err != nil {
			return
		}
	} else {
		file, err := ioutil.ReadFile(abs + "/" + "html/index.html")
		if err != nil {
			panic("open conf file error")
		}
		defaultHtml = string(file)
	}
}

func GetConfig() *AppConfig {
	return config
}

func GetDefaultHtml() string {
	return defaultHtml
}
